package com.wyt.common.jsch;

import java.io.*;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName ProcessUtils
 * @Description: TODO
 * @Author wangyongtao
 * @Date 2023/4/2 13:52
 * @Version 1.0
 **/
public class ProcessUtils {

    /**
     * 1、Process提供了WaitFor和getInputStream两个方法，这两个方法都是阻塞java线程
     * 2、Runtime、ProcessBuilder 区别：
     * ProcessBuilder.start() 和 Runtime.exec()传递的参数有所不同，
     */


    public static void processBuilderTest() {
        try {
            List<String> cmds = Arrays.asList("jps");
            ProcessBuilder builder = new ProcessBuilder();
//            builder.redirectErrorStream(true); 合并错误流到正常输出流（待测试）
            builder.command(cmds);
            Process process = builder.start();

            //1、从进程获取正常数据
            BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
            System.out.println("运行命令：" + cmds.stream().collect(Collectors.joining(";")));
            String tmp;
            while ((tmp = input.readLine()) != null) {
                System.out.println("正常信息：" + tmp);
            }

            //2、从进程获取错误数据
            BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            while ((tmp = error.readLine()) != null) {
                System.out.println("错误信息：" + tmp);
            }

            //3、向进程输入数据
//            BufferedWriter output = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
//            output.write("");
//            output.flush();

            System.out.println("执行命令返回码：" + process.exitValue());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void runTimeTest() {
        try {
            String[] cmds = new String[]{"jps"};
            Process process = Runtime.getRuntime().exec(cmds);

            //1、从进程获取正常数据
            BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
            System.out.println("运行命令：" + Arrays.asList(cmds).stream().collect(Collectors.joining(";")));
            String tmp;
            while ((tmp = input.readLine()) != null) {
                System.out.println("正常信息：" + tmp);
            }

            //2、从进程获取错误数据
            BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            while ((tmp = error.readLine()) != null) {
                System.out.println("错误信息：" + tmp);
            }

            //3、向进程输入数据
//            BufferedWriter output = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
//            output.write("");
//            output.flush();

            System.out.println("执行命令返回码：" + process.exitValue());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        runTimeTest();
    }


}